


import React from 'react';
import {
  Alert
} from 'react-native';

import WebIM from '../huanxin/Lib/WebIM';
import BaseModel from './BaseModel';
import Constants from '../common/Constants';
import ToastUtils from '../common/ToastUtils';

export default class IMModel extends BaseModel {
  constructor(props) {
    super(props);

    this.sendGroupText = this.sendGroupText.bind(this);
    this.checkConnected = this.checkConnected.bind(this);
    this.getLinker = this.getLinker.bind(this);
    this.getUnreadedMsgNum = this.getUnreadedMsgNum.bind(this);
    this.getUnreadedMsgNumByGroupId = this.getUnreadedMsgNumByGroupId.bind(this);
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.callback = null;
    this._updateCallDic = {};
    this.imLoginMsg = {connected:false};
    this.groupChatMsg = {};

    this._linkers = {};

    this._isConnected = true;
  }

  setup(dataManager, callback) {
    // var account = {userName:"58d814caffc3c42e09ae18e0",pwd:"rB6PskM8sJ/k9fEb"}
    console.log("IMModel setup");

    var self = this;
    this.dataManager = dataManager;
    WebIM.conn.listen({
      // xmpp连接成功
      onOpened: (msg) => {
        console.log("onOpened",msg);
        self.imLoginMsg = {connected:true};
        // 出席后才能接受推送消息
        WebIM.conn.setPresence();
      },
      // 出席消息
      onPresence: (msg) => {
        // ToastUtils.show("onPresence:" + JSON.stringify(msg));
        console.debug('onPresence', msg)
        switch (msg.type) {
          case 'subscribe':
            // 加好友时双向订阅过程，所以当对方同意添加好友的时候
            // 会有一步对方自动订阅本人的操作，这步操作是自动发起
            // 不需要通知提示，所以此处通过state=[resp:true]标示
            if (msg.status === '[resp:true]') {
              return
            }

            // store.dispatch(SubscribeActions.addSubscribe(msg))
            break;
          case 'subscribed':
            // store.dispatch(RosterActions.getContacts())
            // Alert.alert(msg.from + ' ' + I18n.t('subscribed'))
            break;
          case 'unsubscribe':
            // TODO: 局部刷新
            // store.dispatch(RosterActions.getContacts())
            break;
          case 'unsubscribed':
            // 好友退订消息
            // store.dispatch(RosterActions.getContacts())
            // Alert.alert(msg.from + ' ' + I18n.t('unsubscribed'))
            break;
        }
      },
      // 各种异常
      onError: (error) => {
        // ToastUtils.show(JSON.stringify(error));
        console.log(error)
        // 16: server-side close the websocket connection
        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED) {
          console.log('WEBIM_CONNCTION_DISCONNECTED', WebIM.conn.autoReconnectNumTotal, WebIM.conn.autoReconnectNumMax);
          // if (WebIM.conn.autoReconnectNumTotal < WebIM.conn.autoReconnectNumMax) {
          //   return;
          // }
          self.imLoginMsg.connected = false;
          self.login(Constants.USER.user_id,Constants.USER.im_passwd);
          // Alert.alert('Error', 'server-side close the websocket connection')
          // NavigationActions.login()
          return;
        }
        // 8: offline by multi login
        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_ERROR) {
          console.log('WEBIM_CONNCTION_SERVER_ERROR');
          Alert.alert('聊天帐号在其他地方登录');
          // NavigationActions.login()
          return;
        }
        if (error.type == 1) {
          let data = error.data ? error.data.data : ''
          // data && Alert.alert('聊天接入失败，请联系管理员');
          console.log('聊天接入失败，请联系管理员');
           self.imLoginMsg.connected = false;
          // store.dispatch(LoginActions.loginFailure(error))
        }
      },
      // 连接断开
      onClosed: (msg) => {
        // ToastUtils.show("连接断开");
        console.log('onClosed')
        self.imLoginMsg.connected = false;
      },
      // 更新黑名单
      onBlacklistUpdate: (list) => {
        // store.dispatch(BlacklistActions.updateBlacklist(list))
      },
      // 文本信息
      onTextMessage: (message) => {
        // ToastUtils.show("onTextMessage:" + JSON.stringify(message));
        if(message.type == "groupchat"){
          console.log('onGroupchatMessage', message)
          if(!self.groupChatMsg[message.to]){
            self.groupChatMsg[message.to] = [];
          }
          message.appType = "txt";
          message.readed = false;
          self.groupChatMsg[message.to].push(message);
          if(self.groupChatMsg[message.to].length > 100){
            self.groupChatMsg[message.to].splice(0,1);
          }
          self._updateCallDic[message.to] && self._updateCallDic[message.to](true, self.groupChatMsg[message.to]);
        }else {
          console.log('unkownImMsg', message);
        }
        // store.dispatch(MessageActions.addMessage(message, 'txt'))
      },
      onPictureMessage: (message) => {
        // store.dispatch(MessageActions.addMessage(message, 'img'))
         if(message.type == "groupchat"){
          console.log('onGroupchatMessage', message)
          if(!self.groupChatMsg[message.to]){
            self.groupChatMsg[message.to] = [];
          }
          message.appType = "pic";
          message.readed = false;
          self.groupChatMsg[message.to].push(message);
          if(self.groupChatMsg[message.to].length > 100){
            self.groupChatMsg[message.to].splice(0,1);
          }
          self._updateCallDic[message.to] && this._updateCallDic[message.to](self.groupChatMsg[message.to]);
        }else {
          console.log('unkownImMsg', message);
        }
      }
    })
    // this.login(account.userName,account.pwd);
    // this.login("914569364","123123");
    if(Constants.USER.user_id) {
      this.login(Constants.USER.user_id,Constants.USER.im_passwd);
    }
    callback();
  }

  setPresence() {
    WebIM.conn.setPresence();
  }

  login(userName, pwd){
    if(this.checkConnected()) {
      WebIM.conn.close();
    }
     WebIM.conn.open({
        apiUrl: WebIM.config.apiURL,
        user: userName,
        pwd: pwd,
        //  accessToken: password,
        appKey: WebIM.config.appkey
      })
  }

  logout() {
    if(this.checkConnected()) {
      WebIM.conn.close();
    }
  }

  checkConnected(){
    return this.imLoginMsg.connected;
  }

  getUnreadedMsgNum(callback) {
    var count = 0;
    for(var key in this.groupChatMsg) {
      for (var i = 0; i < this.groupChatMsg[key].length; i++) {
        if(this.groupChatMsg[key][i].readed === false) {
          count++;
        }
      }
    }
    callback(count);
  }

  //获取某个群聊的未读条数
  getUnreadedMsgNumByGroupId(groupId) {
    var unreadNum = 0;
    if(this.groupChatMsg[groupId]) {
      for (var i = 0; i < this.groupChatMsg[groupId].length; i++) {
        if(this.groupChatMsg[groupId][i].readed === false) {
          unreadNum++;
        }
      }
    }
    return unreadNum;
  }

  // im群组Id
  bindGroup(groupId, updateCall){
    this._updateCallDic[groupId] = updateCall;
    if(this.groupChatMsg[groupId] == null || this.groupChatMsg[groupId] == undefined){
      // let popMsg = this.groupChatMsg[groupId].concat();
      // this.groupChatMsg[groupId].splice(0,popMsg.length);
      this.groupChatMsg[groupId] = [];
    }
    this._updateCallDic[groupId](true, this.groupChatMsg[groupId]);
  }

  unBindGroup(groupId){
    if(this._updateCallDic[groupId]) {
      this._updateCallDic[groupId] = null;
    }
  }

    // sendRequestQuanziAllList(data, callback) {
  //   var url = Config.serverUrl + "/boards?type=2&page="+data.page+"&page_size=10&sort_id=1";
  //   this.sendGet(url, callback);
  // }

  sendGroupText(myOption, callback) {
    if(!this.groupChatMsg[myOption.to]){
      this.groupChatMsg[myOption.to] = [];
    }

    var self = this;
    var id = WebIM.conn.getUniqueId();            // 生成本地消息id
    var msg = new WebIM.message('txt', id); // 创建文本消息
    var option = {roomType: false,
                  chatType: 'chatRoom',
                  success: function(){
                    this.isSelf = true;
                    // ToastUtils.show("success:" + JSON.stringify(this.msg) + "  " + myOption.to + " ==  " + JSON.stringify(self.groupChatMsg));
                    if(Constants.USER){
                      this.avatar_url = Constants.USER.avatar_url;
                      this.nick = Constants.USER.nick;
                    }
                    self.groupChatMsg[myOption.to].push(this);
                    self._updateCallDic[myOption.to](true, self.groupChatMsg[myOption.to]);
                    callback(true);
                  },
                  fail: function () {
                    // Alert.alert("failed:" + myOption.to + " ==  " + JSON.stringify(self.groupChatMsg));
                    // ToastUtils.show("failed:" + myOption.to + " ==  " + JSON.stringify(self.groupChatMsg));
                     console.log('failed');
                     self._updateCallDic[myOption.to](false, self.groupChatMsg[myOption.to]);
                     callback(false);
                  }
                };
  var finalOptions = {...option, ...myOption};
  msg.set(finalOptions);
  msg.setGroup('groupchat');
  WebIM.conn.send(msg.body);
}

// sendPrivateText(myOption) {
//     var id = WebIM.conn.getUniqueId();            // 生成本地消息id
//     var msg = new WebIM.message('txt', id); // 创建文本消息
//     var option = {roomType: false,
//                   success: function (id, serverMsgId) {
//                      console.log('send sendPrivateText text success');
//                   },
//                   fail: function () {
//                      console.log('sendPrivateText failed');
//                   }
//                 };
//    var finalOptions = {...option, ...myOption};
//     msg.set(finalOptions);
//     msg.setGroup('singleChat');
//     WebIM.conn.send(msg.body);
// }


  ////////linkers
  getLinker(linkerType, talkerId, classObject, params) {
    let key = linkerType + "00000" + talkerId;
    if(this._linkers[key] == undefined) {
       this._linkers[key] = new classObject(params);
    }
    return this._linkers[key];
  }
}
